<?php
namespace App\Service;

use App\Model\Applet;
use App\Model\AppletCompany;
use App\Model\AppletPlayletRel;
use App\Model\AuthRole;
use App\Model\MenuRole;
use App\Model\Playlet;
use App\Vilidate\MenuController;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use GuzzleHttp\Client;
use Hyperf\Utils\ApplicationContext;
use Hyperf\DbConnection\Db;
use App\Model\Company;
use App\Model\Module;
use App\Model\Menu;
use App\Model\MenuControl;
use PhpParser\Node\Expr\Cast\Object_;
use Hyperf\HttpServer\Contract\RequestInterface;
class CommicService
{


    public static $commonStatus = [
        '0'       => '禁用',
        '1'       => '正常',
        '2'       => '隐藏',
        '3'       => '重置密码',
    ];

    public static $dramaStatus = [
        '0'       => '待审核',
        '1'       => '审核中',
        '2'       => '最终失败',
        '3'       => '审核通过',
        '4'       => '驳回重填',
        '5'       => '系统错误',
    ];

    public static $albumStatus = [
        '0'       => '待审核',
        '1'       => '审核中',
        '2'       => '最终失败',
        '3'       => '审核通过',
        '4'       => '驳回重填',
        '5'       => '系统错误',
    ];

    public static $templateType = [
        '1'       => '普通模板',
        '2'       => '挽留模板'
    ];

    public static $recentBubbleText = [
        '1' => '有福利',
        '2' => '领福利',
        '3' => '免费看',
        '4' => '有优惠'
    ];

    public static $jumpText = [
        '1' => '去使用',
        '2' => '去领取',
        '3' => '免费看',
        '4' => '领优惠'
    ];
    public function generateRandomString($length = 10) {
        $characters = '2345678abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        return substr(sha1($string), 0, $length);
    }
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->httpclient = new Client();
        $this->request = ApplicationContext::getContainer()->get(RequestInterface::class);
    }
    public function response($code, $msg = '', $data = '')
    {
        if (is_array($msg)) {
            $msg = implode(' ', array_column($msg, 0));
        }

        return [
            'code'    => $code,
            'data'    => $data,
            'message' => $msg,
        ];
    }

    public function getMenuList(Object $userInfo = null){
        //获取所有菜单

        $menus = Menu::query()->get()->toArray();
        $modules = Module::query()->where(['status' => Module::STATUS_SHOW])->select(['id','name','label','icon'])->get();
        $menuControls = MenuControl::query()->select(['id','controller','name','sort','icon'])->get();
        $controlKeyVal = array();
        foreach ($menuControls as $menuControl){
            $controlKeyVal[$menuControl->controller] = $menuControl->toarray();
        }
        $modulesKeyVal = array();
        foreach ($modules as $module){
            $modulesKeyVal[$module->id] = $module->toarray();
        }
        //查询这个人的角色
        $roleIds = $userInfo->roles_ids;
        $roleIds = explode(',',$roleIds);

        $roleInfo = AuthRole::query()->whereIn('id',$roleIds)->first();

        if($roleInfo->is_admin != 1){

           $menuIds =  MenuRole::query()->whereIn('auth_roles_id',$roleIds)->pluck('menu_id')->toArray();
           $menuIds = array_unique($menuIds);
           $menus = Menu::query()->whereIn('id',$menuIds)->get()->toArray();
        }

        $treeData = array();
        $permissions = array();
        $menuList = array();

        foreach ($menus as $menu) {
            $module                                              = $modulesKeyVal[$menu['module_id']];
            $controller                                          = $menu['controller'];
            $url = $module['name'].':'.$menu['controller'].':'.$menu['action'];
            $permissions[] = $url;
            if($menu['status'] != Menu::STATUS_SHOW){
                continue;
            }
            $treeData[$module['name']]['module_id']              = $module['id'];
            $treeData[$module['name']]['name']                   = $module['label'];
            $treeData[$module['name']]['icon']                   = $module['icon'];

            $treeData[$module['name']]['children'][$controller] = [
                'menuId'     => $menu['id'],
                'icon'       => $controlKeyVal[$controller]['icon'],
                'name'       => $controlKeyVal[$controller]['name'],
                'controller' => $menu['controller'],
                'url'        => $module['name'].'/'.$menu['controller'],
                'sort'       => $controlKeyVal[$controller]['sort'],
            ];
        }
        if(!empty($treeData)){
            foreach ($treeData as $tree){
                $treeInfo =[
                    'menuId' => $tree['module_id'],
                    'name'   => $tree['name'],
                    'url'    =>null,
                    'icon'   => $tree['icon'] ?? '',
                ];
                if(!empty($tree['children'])){
                    $childrens = array_values($tree['children']);
                }

                $sort = array_column($childrens,'sort');
                array_multisort($sort,SORT_DESC,$childrens);
                $treeInfo['children'] = $childrens;
                $menuList[] = $treeInfo;
            }
        }
        return['permissions' =>array_unique($permissions),'menuList' => $menuList];

    }

    public function getUserAppletInfo($is_applet = 1){
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $access_token = $request->getHeader('Mema-Token')[0];

        $redisKey = 'userInfo:'.$access_token;
        //查找redis上是否有对应的token
        $userInfo = $this->redisService->get($redisKey);

        $userInfo = json_decode($userInfo,true);

        if($is_applet == 1){
            $appletInfo = $userInfo['applet'];
            $appletId = array();
            if(!empty($appletInfo)){

                foreach ($appletInfo as $item){
                    $appletId[] = $item['value'];
                }
            }
            if(!empty($appletId)){

                return $appletId;
            }
        }else{

            $is_admin = 0;
            $is_statistical = 0;
            $is_check_user_order = 0;
            if(!empty($userInfo['is_admin'])){
                $is_admin = $userInfo['is_admin'];
            }
            if(!empty($userInfo['is_statistical'])){
                $is_statistical = $userInfo['is_statistical'];
            }
            if(!empty($userInfo['is_check_user_order'])){
                $is_check_user_order = $userInfo['is_check_user_order'];
            }

            $userInfo = $userInfo['user'];
            $userInfo['role']['is_admin'] = $is_admin;
            $userInfo['role']['is_statistical'] = $is_statistical;
            $userInfo['role']['is_check_user_order'] = $is_check_user_order;
            return $userInfo;
        }



        return [];
    }


    //获取用户的公司，获取对应的公司所有的小程序
    public function getAppletInfo(Object $userInfo = null,$type=0){
        //获取用户的所属公司

        $appletData = array();
        $companyInfo = Company::query()->where(['id' => $userInfo->company_id ])->first();
        if(!empty($companyInfo)){
            //获取公司所绑定的小程序
           $appletIds = AppletCompany::query()->where(['company_id' => $companyInfo->id])->pluck('applet_id');
           if(!empty($appletIds)){

              $appletInfo =  Applet::query()->whereIn('id',$appletIds)->select(['id as value','name as label'])->get();
              if(!empty($appletInfo)){

                    $returnData[] = ['value' => 1,'label' => '全部小程序'];
                    $appletInfo = array_merge($returnData,$appletInfo->toArray());

                    return $appletInfo;
              }
           }
        }

        return $appletData;

    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }

    /**
     * 数字转汉字
     */
    public function numToStr($num)
    {
        $chiNum = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        $chiUni = array('','十', '百', '千', '万', '亿', '十', '百', '千');
        $chiStr = '';
	    $num_str = (string)$num;

	    $count = strlen($num_str);
        // 按字符串处理
        $last_flag = true;//上一个 是否为0
        $zero_flag = true; //是否第一个
        $temp_num = null; //临时数字
        $chiStr = '';//拼接结果
        if ($count == 2) {//两位数
           $temp_num = $num_str[0];
           $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
           $temp_num = $num_str[1];
           $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];

        }else if($count > 2){

            $index = 0;
            for ($i=$count-1;$i >= 0;$i--) {
                $temp_num = $num_str[$i];
                if ($temp_num == 0) {
                    if (!$zero_flag && !$last_flag ) {
                        $chiStr = $chiNum[$temp_num]. $chiStr;
                        $last_flag = true;
                    }
                }else{
                    $chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
                    $zero_flag = false;
                    $last_flag = false;
                }
                $index ++;
            }
        }else{
            $chiStr = $chiNum[$num_str[0]];
        }
        return $chiStr;
    }


    /**
     * 抖音获取跳转链接
     */
    public function dygenerateLink($appletData,$query){

        $applet_id = $appletData->id;
        $app_id = $appletData->app_id;
        $app_secret = $appletData->app_secret;
        $accessToken = $this->getDyAccessToken($applet_id);
        if(!empty($accessToken)){
           $linkData = $this->generateLink($app_id,$query,$accessToken);
           if(!empty($linkData)){
                return $linkData['url_link'];
           }
        }
        return '';
    }

    public function generateLink($app_id,$query,$accessToken){
        $limit = 100;
        $params         = [
            "app_name"    => 'douyin',
            "app_id"      => $app_id,
            "path"  => 'pages/videopage/videopage',
            "query" => $query,
            "expire_time" => time()+(86400*180)
        ];
        $linkUrl = 'https://open.douyin.com/api/apps/v1/url_link/generate/';
        //获取生成链接
        $result  = $this->dyrequest($params, $linkUrl,'POST',$accessToken);

        if($result['err_no'] == 0){
            return $result['data'];
        }
        return false;
    }
    public function getDyAccessToken($applet_id){
        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');
        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $accessToken = "";
        }
        return $accessToken;
    }


    /**
     * 传入数组进行HTTP POST请求
     */
    function dyrequest(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}